import React, { useState, useEffect } from "react";
import { Tree, message } from "antd";
import axios from "axios";
import "../mock/orgtree.js";
import "../mock/org3145.js";
import "../mock/org3146.js";

/**更新树 */
function updateTreeData(list, key, children) {
  return list.map((node) => {
    if (node.key === key) {
      return { ...node, children };
    }
    if (node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children),
      };
    }
    return node;
  });
}

function OrgTree(props) {
  /**外部参数 */
  const { treeData, treeOnSelect, setTreeData, isHost } = props;
  /**机构树 */
  const [TData, setTData] = useState(treeData);

  var newTree = [];
  /**获取机构树 */
  async function getNewTree(orgId) {
    let orgUrl = "orgTree.rst?id=" + orgId;
    let res = await axios.get(orgUrl);
    let response = res.data;
    // let response = res;
    if (response.resultCode === 0) {
      let data = response.result.data;
      const NewTree = data.map((data, index) => {
        return {
          key: data.id,
          title: data.text,
          isLeaf: data.state === "closed" ? false : true,
        };
      });
      newTree = NewTree;
    } else {
      message.error("数据请求失败");
    }
  }

  const onLoadData = ({ key, children }) =>
    new Promise(async (resolve) => {
      if (children) {
        resolve();
        return;
      }
      /**请求到子级机构 */
      await getNewTree(key);
      /**对比更新 */
      setTData((origin) => updateTreeData(origin, key, newTree));
      /**外部方法 */
      setTreeData(TData);
      resolve();
    });

  useEffect(() => {
    /**加载初级机构 */
    (async function () {
      await getNewTree("");
      setTData(newTree);
    })();
  }, []);

  const OnSelect = (value) => {
    if (value[0]) {
      /**取消勾选不发请求 */
      treeOnSelect(isHost, value);
    }
  };
  return (
    <Tree
      height={200}
      dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
      treeData={TData}
      placeholder="Please select"
      onSelect={OnSelect}
      loadData={onLoadData}
    />
  );
}

export default OrgTree;
